// 无缝滚动轮播

export const userScolle = (list, num) => {
  // 滚动速度
  const SPEED = 0.8;
  // 停止标记
  let isSTOP = false;
  // 报错标记
  let ERRORStatus = false;
  // 添加元素
  const AppendEl = () => {
    try {
      // 拿到子元素克隆并追加到父元素
      const ChildEl = Array.from(list.value.children);
      if (ChildEl.length > num) {
        ChildEl.forEach((item) => {
          // 拿到当前元素
          const currentEl = item.cloneNode(true);
          // 追加到父元素
          list.value.appendChild(currentEl);
        });
      }
    } catch (e) {
      list.value.style.overflow = "hidden";
      ERRORStatus = true;
    }
  };
  // 处理滚动
  const HanderStart = () => {
    // 若有报错或停止标记则阻止当前操作
    if (ERRORStatus || isSTOP || list.value.children.length < num + 1) return;
    // 因为滚动到一半的时候添加元素，所以让滚动从0开始
    const { scrollTop, scrollHeight } = list.value;
    if (scrollTop >= MaxScrollTop(scrollHeight / 2)) {
      list.value.scrollTop = 0;
    }
    list.value.scrollTop += SPEED;
    requestAnimationFrame(HanderStart);
  };
  // 计算滚动的最大值
  const MaxScrollTop = () => {
    const { scrollHeight, clientHeight } = list.value;
    return scrollHeight - clientHeight;
  };

  // 鼠标移入
  const mouseEnter = () => {
    isSTOP = true;
  };
  // 鼠标移出
  const mouseLeave = () => {
    isSTOP = false;
    HanderStart();
  };
  onMounted(() => {
    setTimeout(() => {
      AppendEl();
      HanderStart();
    }, 1000);

    // 监听鼠标移入
    list.value.addEventListener("mouseenter", () => {
      mouseEnter();
    });
    // 监听鼠标移出
    list.value.addEventListener("mouseleave", () => {
      mouseLeave();
    });
  });
};
